/**
 * 
 */
package com.zy.cat.service.impl;

import java.text.SimpleDateFormat;
import java.time.LocalDate;
import java.time.LocalDateTime;
import java.time.LocalTime;
import java.time.format.DateTimeFormatter;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Calendar;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.stream.Collectors;

import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import com.alibaba.fastjson.JSON;
import com.zy.cat.common.utils.TJKUtils;
import com.zy.cat.dao.Dao;
import com.zy.cat.entity.dev.CatDevTreeTaskConfig;
import com.zy.cat.entity.dev.CatDevTreeTaskRecord;
import com.zy.cat.entity.dev.CatDevUserInfo;
import com.zy.cat.entity.dev.CatDevUserTaskConfig;
import com.zy.cat.entity.dev.CatDevUserTaskRecord;
import com.zy.cat.entity.dev.act.CatDailyDrawAwardeeOrder;
import com.zy.cat.entity.dev.act.resp.CatDailyDrawDetailResp;
import com.zy.cat.entity.dev.garden.CatTreeOrder;
import com.zy.cat.entity.dev.garden.CatTreeResult;
import com.zy.cat.entity.dev.garden.CatUserTree;
import com.zy.cat.entity.dev.garden.CatUserTreeGrade;
import com.zy.cat.entity.dev.garden.CatUserTreeTask;
import com.zy.cat.entity.dev.garden.Tree;
import com.zy.cat.entity.dev.garden.repository.CatTreeOrderRepository;
import com.zy.cat.entity.dev.garden.repository.CatTreeRepository;
import com.zy.cat.entity.dev.garden.repository.CatUserTreeGradeRepository;
import com.zy.cat.entity.dev.garden.repository.CatUserTreeRepository;
import com.zy.cat.entity.dev.garden.repository.CatUserTreeRewardRepository;
import com.zy.cat.entity.dev.garden.repository.CatUserTreeTaskRepository;
import com.zy.cat.entity.dev.garden.repository.CatUserTreeWaterRepository;
import com.zy.cat.entity.dev.garden.repository.TreeResultRepository;
import com.zy.cat.entity.dev.garden.resp.CatTreeDetailResp;
import com.zy.cat.entity.dev.garden.resp.CatUserTreeGradeResp;
import com.zy.cat.entity.dev.garden.resp.CatUserTreeGradeResp.UserTreeGrade;
import com.zy.cat.entity.dev.garden.resp.CatUserTreeHistoryResp;
import com.zy.cat.entity.dev.garden.resp.CatUserTreeResp;
import com.zy.cat.entity.dev.garden.resp.CatUserTreeTaskRewardResp;
import com.zy.cat.entity.dev.garden.resp.CatUserTreeWateringResp;
import com.zy.cat.entity.dev.repository.CatDevFertilizerVideoHistoryRepository;
import com.zy.cat.entity.dev.repository.CatDevTreeTaskConfigRepository;
import com.zy.cat.entity.dev.repository.CatDevTreeTaskRecordRepository;
import com.zy.cat.entity.dev.repository.CatDevUserInfoRepository;
import com.zy.cat.entity.dev.repository.CatDevUserTaskRecordRepository;
import com.zy.cat.entity.dev.resp.CatDevRemitRecordResp;
import com.zy.cat.entity.dev.resp.CatDevWelfareInfoResp.UserTaskData;
import com.zy.cat.entity.game.repository.CatDevSignedBeansHistoryRepository;
import com.zy.cat.entity.mall.CatGoodsCouponHistory;
import com.zy.cat.entity.resp.RSPE;
import com.zy.cat.entity.wx.WxUserInfo;
import com.zy.cat.entity.wx.repository.WxUserInfoRepository;
import com.zy.cat.service.CacheService;
import com.zy.cat.service.CatDevTreeService;

import lombok.extern.slf4j.Slf4j;

/**
 * @author sunyuancui
 * @date 2020年12月24日
 * 
 */

@Slf4j
@Service
public class CatDevTreeServiceImpl implements CatDevTreeService {

	@Autowired
	CacheService cacheService;

	@Autowired
	CatUserTreeRepository catUserTreeRepository;

	@Autowired
	CatDevUserTaskRecordRepository newUserTaskRecordRepository;

	@Autowired
	CatDevTreeTaskRecordRepository newTreeTaskRecordRepository;

	@Autowired
	CatDevTreeTaskConfigRepository catDevTreeTaskConfigRepository;

	@Autowired
	CatDevSignedBeansHistoryRepository signedBeansHistoryRepository;

	@Autowired
	CatUserTreeGradeRepository catUserTreeGradeRepository;

	@Autowired
	CatUserTreeWaterRepository catUserTreeWaterRepository;

	@Autowired
	CatUserTreeRewardRepository catUserTreeRewardRepository;

	@Autowired
	CatDevFertilizerVideoHistoryRepository fertilizerVideoHistoryRepository;

	@Autowired
	CatTreeRepository catTreeRepository;

	@Autowired
	CatUserTreeTaskRepository catUserTreeTaskRepository;

	@Autowired
	WxUserInfoRepository wxUserInfoRepository;

	@Autowired
	CatDevUserInfoRepository catDevUserInfoRepository;

	@Autowired
	TreeResultRepository treeResultRepository;

	@Autowired
	CatTreeOrderRepository catTreeOrderRepository;

	@Autowired
	Dao<Tree> userTreeDao;

	@Autowired
	Dao<UserTreeGrade> gradeDao;

	@Autowired
	Dao<Tree> treeDao;

	@Autowired
	Dao<CatUserTreeResp> catUserTreeDao;

	@Autowired
	Dao<CatUserTreeHistoryResp> catUserTreeHistoryDao;

	@Autowired
	Dao<CatUserTreeWateringResp> waterDao;

	@Autowired
	Dao<CatDevUserInfo> catDao;

	/**
	 * 获取果园数据
	 */
	@Override
	public List<CatUserTreeResp> getTreeData(Integer rtype, String pid) {
		// TODO Auto-generated method stub
		// 通过pid获取用户果园信息
		List<CatUserTreeResp> treeList = catUserTreeRepository.findByPid(pid);
		for (CatUserTreeResp catUserTreeResp : treeList) {
			// 判断用户是否是首次种植
			// 如果是首次种植
			if (catUserTreeResp.getFirstPlant() == 0) {
				List<Tree> plantList = catTreeRepository.findAll();
				catUserTreeResp.setPlantList(plantList);
			}
			// catUserTreeResp.setFirstPlant(1);
			// 判断,当所施肥料数大于当前等级所需肥料时，等级加1
			if (catUserTreeResp.getAfertilizer() > catUserTreeResp.getFertilizerTotal()) {
				catUserTreeResp.setLevel(catUserTreeResp.getLevel() + 1);
				// 根据当前等级，获取当前等级数据
				List<CatUserTreeGradeResp> resp = catUserTreeGradeRepository.findAll();
				for (CatUserTreeGradeResp catUserTreeGradeResp : resp) {
					if (catUserTreeResp.getLevel() == catUserTreeGradeResp.getLevel()) {
						catUserTreeResp.setFertilizerTotal(catUserTreeGradeResp.getFertilizerTotal());
					}
				}
				catUserTreeRepository.saveAndFlush(catUserTreeResp);
			}
		}
		if (treeList == null || treeList.size() == 0) {
			CatUserTreeResp resp = new CatUserTreeResp(pid);
			resp.setFirstPlant(0);
			treeList = new ArrayList<>();
			treeList.add(resp);
		}
		return treeList;
	}

	/**
	 * 开始种树(新用户初始化信息)
	 */
	@Override
	public List<CatUserTreeResp> getTree(String pid, Integer id) {
		// TODO Auto-generated method stub
		List<CatUserTreeResp> result = new ArrayList<>();
		// 获取果树
		Tree tree = catTreeRepository.findByid(id);
		String content = tree.getContent();
		String title = tree.getTitle();
		String icUrl = tree.getIcUrl();
		// 创建一个新的果园数据
		CatUserTreeResp resp = new CatUserTreeResp(pid);
		// 将种植状态设为1
		resp.setFirstPlant(1);
		// 插入果树信息
		resp.setId(id);
		resp.setContent(content);
		resp.setTitle(title);
		resp.setIcUrl(icUrl);
		resp.setPid(pid);
		// 初始化用户果园信息
		resp.setAfertilizer(600);
		resp.setFertilizer(0);
		resp.setFertilizerTotal(3500);
		resp.setLevel(1);
		resp.setOnceFertilizer(600);
		if (resp != null) {
			catUserTreeRepository.saveAndFlush(resp);
		}
		result.add(resp);
		return result;
	}

	/**
	 * 获取用户果园任务数据()
	 */
	@Transactional
	@Override
	public CatUserTreeResp getTreeTask(Integer rtype, String pid) {
		log.debug("-->getTreeTask ");

		// 创建一个新的任务数据表(新人任务和每日任务)
		CatUserTreeResp result = new CatUserTreeResp(pid);
		// 通过pid获取用户果园数据
		List<CatUserTreeResp> resp = catUserTreeRepository.findByPid(pid);
		for (CatUserTreeResp catUserTreeResp : resp) {
			result.setLevel(catUserTreeResp.getLevel());
			result.setFertilizerTotal(catUserTreeResp.getFertilizerTotal());
			result.setAfertilizer(catUserTreeResp.getAfertilizer());
			result.setFertilizer(catUserTreeResp.getFertilizer());
			result.setOnceFertilizer(catUserTreeResp.getOnceFertilizer());
			result.setFirstPlant(catUserTreeResp.getFirstPlant());
			result.setId(catUserTreeResp.getAfertilizer());
			result.setTitle(catUserTreeResp.getTitle());
			result.setContent(catUserTreeResp.getContent());
			result.setIcUrl(catUserTreeResp.getIcUrl());
		}
		// 通过pid获取用户信息
		CatDevUserInfo userInfo = getCatDevUserInfoByPid(pid);
		// 获取新人任务列表
		List<CatDevTreeTaskRecord> list = newTreeTaskRecordRepository.findByPidAndTaskAttributeOrderByTaskType(pid, 0);
		log.debug("-->getTreeTask newUserTask:" + list.size());
		// 判断
		if (list == null || list.size() == 0) {
			// 新建新人任务
			List<CatDevTreeTaskConfig> configList = catDevTreeTaskConfigRepository.findByTaskAttributeOrderByTypeId(0);
			list = configList.stream().map(config -> {
				return new CatDevTreeTaskRecord(config.getTypeId(), pid, config.getFertilizerNum(),
						TJKUtils.DateTimeYMD(), 0, config.getTaskContent(), config.getTaskNum(), config.getTaskTitle(),
						config.getTaskPic(), config.getTaskBtn());
			}).collect(Collectors.toList());
			newTreeTaskRecordRepository.saveAll(list);
			newUserTaskRecordRepository.flush();
		}
		// 检验新人任务是否完成
		List<CatUserTreeTask> collect = createNewUserTaskData(list, userInfo);
		result.setNewUserTaskData(collect);

		// 获取每日任务列表（查询当天日期的任务
//	    LocalDateTime today_start = LocalDateTime.of(LocalDate.now(), LocalTime.MIN);//当天零点
//	    LocalDateTime today_end = LocalDateTime.of(LocalDate.now(), LocalTime.MAX);//当天零点

		String td_st_str = TJKUtils.DateTimeYMD();
		List<CatDevTreeTaskRecord> everydayList = newTreeTaskRecordRepository
				.queryByPidAndTaskAttributeAndCtimeOrderByTaskType(pid, 1, td_st_str);
		log.debug("-->getTreeTask everydayTask:" + everydayList.size());
		// 判断
		if (everydayList == null || everydayList.size() == 0) {
			// 新建每日任务
			List<CatDevTreeTaskConfig> taskConfigList = catDevTreeTaskConfigRepository
					.findByTaskAttributeOrderByTypeId(1);
			everydayList = taskConfigList.stream().map(config -> {
				return new CatDevTreeTaskRecord(config.getTypeId(), pid, config.getFertilizerNum(),
						TJKUtils.DateTimeYMD(), 1, config.getTaskContent(), config.getTaskNum(), config.getTaskTitle(),
						config.getTaskPic(), config.getTaskBtn());

			}).collect(Collectors.toList());

			newTreeTaskRecordRepository.saveAll(everydayList);
			// newUserTaskRecordRepository.flush();
		}
		// 校验每日任务是否已完成
		List<CatUserTreeTask> everydayTaskData = createEveryUserTaskData(everydayList, userInfo);
		result.setEverydayTaskData(everydayTaskData);

		return result;
	}

	/**
	 * 将CatDevTreeTaskRecord类型转换为响应类型, 校验新人任务完成情况
	 * 
	 * @param list
	 * @param userInfo
	 * @return
	 */
	private List<CatUserTreeTask> createNewUserTaskData(List<CatDevTreeTaskRecord> list, CatDevUserInfo userInfo) {
		// TODO Auto-generated method stub
		List<CatUserTreeTask> collect = list.stream().map(obj -> {
			CatUserTreeTask taskData = new CatUserTreeTask();
			BeanUtils.copyProperties(obj, taskData);// 前面赋值给后面
			taskData.setTaskType(obj.getTaskType());
			taskData.setTaskNum(obj.getTaskNum());
			// 判断如果奖励已领取或任务已取消，则设置响应参数为不显示
			if (obj.getReceiveStatus() == 1) {
				taskData.setIsShow(0);
				// 任务未完成(新人任务)
			} else if (obj.getTaskStatus() == 0) {
				// 如果是首次下单
				if (obj.getTaskType() == 4) {
					// 判断用户是否已经有订单记录
					Integer number = cacheService.getOrderNumber(userInfo.getPid(), userInfo.getPid(), null);
					if (obj.getTaskStatus() != 1 && number != null && number > 0) {
						// 设置为待领取状态
						obj.setLtime(TJKUtils.DateTime());
						obj.setTaskStatus(1);
						obj.setReceiveStatus(0);
						newTreeTaskRecordRepository.saveAndFlush(obj);
						taskData.setTaskStatus(1);
						taskData.setReceiveStatus(0);

					}
					taskData.setIsShow(1);

				} else if (obj.getTaskType() == 0) {
					// TODO Auto-generated method stub
					// 新人用户奖励
					// 判定用户是否满足新人奖励条件
					if (userInfo.getUtype() == 0 && userInfo.getPid().equals(obj.getPid())) {
						// 设置为待领取状态
						obj.setLtime(TJKUtils.DateTime());
						obj.setTaskStatus(1);
						obj.setReceiveStatus(0);
						newTreeTaskRecordRepository.saveAndFlush(obj);
						taskData.setTaskStatus(1);
						taskData.setReceiveStatus(0);
						taskData.setIsShow(1);
					} else {
						taskData.setIsShow(0);
					}

				} else if (obj.getTaskType() == 2) {
					// 完善手机号
					// 判断用户是否已完善手机号
					List<CatDevUserInfo> phonelist = catDevUserInfoRepository.findByPhone(userInfo.getPhone());
					if (obj.getTaskStatus() != 1 && phonelist != null || phonelist.size() > 0) {
						// 设置为待领取状态
						obj.setLtime(TJKUtils.DateTime());
						obj.setTaskStatus(1);
						obj.setReceiveStatus(0);
						newTreeTaskRecordRepository.saveAndFlush(obj);
						taskData.setTaskStatus(1);
						taskData.setReceiveStatus(0);
					}
					taskData.setIsShow(1);

				} else if (obj.getTaskType() == 3) {
					// 绑定公众号
					// 判断用户是否已绑定微信公众号
					WxUserInfo wxUserInfo = wxUserInfoRepository.findByUnionid(userInfo.getUnionid());
					if (obj.getTaskStatus() != 1 && wxUserInfo != null) {
						// 设置为已完成待领取状态
						obj.setLtime(TJKUtils.DateTime());
						obj.setTaskStatus(1);
						obj.setReceiveStatus(0);
						newTreeTaskRecordRepository.saveAndFlush(obj);
						taskData.setTaskStatus(1);
						taskData.setReceiveStatus(0);
					}
					taskData.setIsShow(1);

				} else {
					// taskData.setIsShow(0);
				}
			} else if (obj.getTaskStatus() == 1 && obj.getReceiveStatus() == 0) {
				// 如果为已完成任务，但未领取的状态
				taskData.setIsShow(1);
			}

			return taskData;

		}).collect(Collectors.toList());
		return collect;
	}

	/**
	 * 将CatDevTreeTaskRecord类型转换为响应类型, 校验每日任务完成情况
	 * 
	 * @param list
	 * @param userInfo
	 * @return
	 */
	private List<CatUserTreeTask> createEveryUserTaskData(List<CatDevTreeTaskRecord> everydayList,
			CatDevUserInfo userInfo) {
		// TODO Auto-generated method stub

		List<CatUserTreeTask> collect = everydayList.stream().map(obj -> {
			log.debug("-->createEveryUserTaskData stream:");
			log.debug("type:" + obj.getTaskType() + " title:" + obj.getTaskTitle());

			CatUserTreeTask taskData = new CatUserTreeTask();
			BeanUtils.copyProperties(obj, taskData);// 前面赋值给后面
			taskData.setTaskType(obj.getTaskType());
			taskData.setTaskTotal(obj.getTaskTotal());
			taskData.setTaskNum(obj.getTaskNum());

			// 判断如果奖励已领取或任务已取消，则设置响应参数为不显示
			if (obj.getReceiveStatus() == 1) {
				taskData.setIsShow(0);
				// 任务未完成
			} else if (obj.getTaskStatus() == 0) {
				// 如果是购买商品
				if (obj.getTaskType() == 14) {
					// 判断用户是否已经有订单记录(当天订单
					Integer number = cacheService.getOrderNumber(userInfo.getPid(), userInfo.getPid(), TJKUtils.DateTimeYMD());
					// 获取创建时间
					String ctime = obj.getCtime().toString();
					// 判断是否是当天订单

					if (number != null && number > 0 && number - obj.getTaskNum() > 0) {
						// 设置为待领取状态
						obj.setLtime(TJKUtils.DateTime());
						obj.setTaskStatus(1);
						obj.setReceiveStatus(0);
						obj.setTaskNum(obj.getTaskNum() + 1);
						newTreeTaskRecordRepository.saveAndFlush(obj);
						taskData.setTaskStatus(1);
						taskData.setReceiveStatus(0);
						taskData.setTaskNum(obj.getTaskNum());
					}
					taskData.setIsShow(1);
				} else {
					// taskData.setIsShow(0);
				}
			} else if (obj.getTaskStatus() == 1 && obj.getReceiveStatus() == 0) {
				// 如果为已完成任务，但未领取的状态
				taskData.setIsShow(1);
			}

			if (taskData.getTaskTotal() > 1) {
				taskData.setTaskTitle(
						taskData.getTaskTitle() + "(" + taskData.getTaskNum() + "/" + taskData.getTaskTotal() + ")");
			}
			return taskData;
		}).collect(Collectors.toList());

		return collect;
	}

	/**
	 * 注册新用户新人任务记录
	 * 
	 * @author sunyuancui
	 * @date 2021-01-06 16:23:34
	 * @param pid
	 */
	private void insertNewUserTask(String pid) {
		// 设置对应奖励的肥料数
		List<CatDevTreeTaskConfig> taskConfigList = catDevTreeTaskConfigRepository.findByTaskAttributeOrderByTypeId(0);
		List<CatDevTreeTaskRecord> list = taskConfigList.stream().map(config -> {
			return new CatDevTreeTaskRecord(config.getTypeId(), pid, config.getFertilizerNum(), TJKUtils.DateTime(), 0,
					config.getTaskContent(), config.getTaskNum(), config.getTaskTitle(), config.getTaskPic(),
					config.getTaskBtn());
		}).collect(Collectors.toList());
		// 批量插入进行
		newTreeTaskRecordRepository.saveAll(list);
		newTreeTaskRecordRepository.flush();
	}

	/**
	 * 获取用户信息
	 */
	@Override
	public CatDevUserInfo getCatDevUserInfoByPid(String pid) {
		String userJson = cacheService.getCatDevUserInfoByPid(pid);
		return StringUtils.isEmpty(userJson) ? null : JSON.parseObject(userJson, CatDevUserInfo.class);
	}

	/**
	 * 获取果树等级信息
	 */
	@Override
	public CatUserTreeGradeResp getTreeLevel() {
		// TODO Auto-generated method stub
		CatUserTreeGradeResp result = new CatUserTreeGradeResp();

		// 1级基数--3500
		int fertilizerTotal = 3500;
		List<UserTreeGrade> treeGradeList = new ArrayList<>();
		for (int level = 1; level <= 15; level++) {
			if (level == 1) {
				fertilizerTotal = 3500;
			} else {
				fertilizerTotal = fertilizerTotal + 500 + 300 * (level - 1);
			}
			// 赋值
			result.setLevelTotal(15);
			result.setOnceFertilizer(600);
			UserTreeGrade treeGrade = new UserTreeGrade();
			treeGrade.setLevel(level);
			treeGrade.setFertilizerTotal(fertilizerTotal);

			treeGradeList.add(treeGrade);
			result.setLevelList(treeGradeList);
			// 保存并刷新
			catUserTreeGradeRepository.saveAndFlush(result);
		}
		return result;
	}

	/**
	 * 
	 * 领取任务奖励
	 */
	@Override
	public CatUserTreeTask getTaskReward(Integer rtype, String pid, CatDevTreeTaskRecord taskRecord) {
		// TODO Auto-generated method stub
		// 获取任务次数
		if (taskRecord.getTaskTotal() >= taskRecord.getTaskNum()) {
			if (taskRecord.getTaskType() != 14) {
				taskRecord.setTaskNum(taskRecord.getTaskNum() + 1);
			}
			if (taskRecord.getTaskTotal() == taskRecord.getTaskNum()) {
				taskRecord.setTaskStatus(1);
				taskRecord.setReceiveStatus(1);
			} else if (taskRecord.getTaskTotal() > taskRecord.getTaskNum()) {
				taskRecord.setTaskStatus(0);
				taskRecord.setReceiveStatus(0);
			}

			// 根据pid获取果园数据
			List<CatUserTreeResp> resp = catUserTreeRepository.findByPid(pid);
			for (CatUserTreeResp catUserTreeResp : resp) {
				// 判断如果任务奖励已领取，则增加肥料数量
				catUserTreeResp.setFertilizer(catUserTreeResp.getFertilizer() + taskRecord.getFertilizerNum());
				catUserTreeRepository.saveAndFlush(catUserTreeResp);
			}
			// 更新时间
			taskRecord.setLtime(TJKUtils.DateTime());
			if (newTreeTaskRecordRepository.saveAndFlush(taskRecord) == null) {
				return null;
			}
		}
		// 完成次数
		if (taskRecord.getTaskTotal() > 1) {
			taskRecord.setTaskTitle(
					taskRecord.getTaskTitle() + "(" + taskRecord.getTaskNum() + "/" + taskRecord.getTaskTotal() + ")");
		}
		CatUserTreeTask treeTask = new CatUserTreeTask();
		BeanUtils.copyProperties(taskRecord, treeTask);
		treeTask.setTaskContent(taskRecord.getTaskContent());
		return treeTask;
	}

	/**
	 * 用户浇水
	 */
	@Override
	public List<CatUserTreeResp> getWatering(Integer rtype, String pid, Integer onceFertilizer) {
		// TODO Auto-generated method stub
		// 获取果园数据
		List<CatUserTreeResp> resp = catUserTreeRepository.findByPid(pid);
		for (CatUserTreeResp catUserTreeResp : resp) {
			// 用户浇水
			if (catUserTreeResp.getLevel() < 15) {
				Integer fertilizer = (catUserTreeResp.getFertilizer() - onceFertilizer);
				Integer aFertilizer = (catUserTreeResp.getAfertilizer() + onceFertilizer);
				catUserTreeResp.setFertilizer(fertilizer);
				catUserTreeResp.setAfertilizer(aFertilizer);
				// 判断,当所施肥料数大于当前等级所需肥料时，等级加1
				if (catUserTreeResp.getAfertilizer() >= catUserTreeResp.getFertilizerTotal()) {
					Integer Afertilizer = catUserTreeResp.getAfertilizer() - catUserTreeResp.getFertilizerTotal();
					catUserTreeResp.setAfertilizer(Afertilizer);
					// 根据当前等级，获取下一等级数据
					catUserTreeResp.setLevel(catUserTreeResp.getLevel() + 1);
					List<CatUserTreeGradeResp> grade = catUserTreeGradeRepository.findAll();
					for (CatUserTreeGradeResp catUserTreeGradeResp : grade) {
						if (catUserTreeResp.getLevel() == catUserTreeGradeResp.getLevel()) {
							catUserTreeResp.setFertilizerTotal(catUserTreeGradeResp.getFertilizerTotal());
						}
					}
				}
			} else {
				if (catUserTreeResp.getLevel() == 15 && catUserTreeResp.getFertilizerTotal() == 42000) {
					catUserTreeResp.setTreeStatus(1);
				}
			}
			// 保存并立即刷新
			catUserTreeRepository.saveAndFlush(catUserTreeResp);
		}
		return resp;

	}

	// 领取水果,填写收货信息
	@Override
	@Transactional
	public CatTreeOrder receiveTree(CatTreeResult treeResult, String recipientName, String recipientPhone, String area,
			String address) {
		// TODO Auto-generated method stub
		treeResult.setTreeStatus(2);
		// 获取果园数据，将果树状态设置为已填单未发货
		List<CatUserTreeResp> resp = catUserTreeRepository.findByPid(treeResult.getPid());
		for (CatUserTreeResp catUserTreeResp : resp) {
			catUserTreeResp.setTreeStatus(2);
		}
		treeResult.setUpdateTime(new Date());
		treeResultRepository.saveAndFlush(treeResult);
		CatTreeOrder treeOrder = catTreeOrderRepository.findByPidAndTreeId(treeResult.getPid(), treeResult.getTreeId());
		if (treeOrder == null) {
			treeOrder = new CatTreeOrder();
			treeOrder.setCreateTime(new Date());
			// treeOrder.setOrderStatus(0);
			treeOrder.setPid(treeResult.getPid());
			treeOrder.setTreeId(treeResult.getTreeId());
		} else {
			treeOrder.setUpdateTime(new Date());
		}
		treeOrder.setRecipientName(recipientName);
		treeOrder.setRecipientPhone(recipientPhone);
		treeOrder.setAddress(address);
		// 设置省市区
		String[] split = area.split(",");
		treeOrder.setProvince(split[0]);
		treeOrder.setCity(split[0]);
		treeOrder.setCounty(split[0]);
		// 保存一条用户信息
		return catTreeOrderRepository.saveAndFlush(treeOrder);

	}

	/**
	 * 删除果园历史种树信息
	 */
	@Override
	public List<CatUserTreeResp> getNextTree(String pid, Integer id) {
		// TODO Auto-generated method stub
		// 获取用户上一次果树状态，如果果树成熟状态是水果送达成功，则将此次种树信息放到历史表中 开始种下一棵树
		// 1.获取用户上一次果树状态
		List<CatUserTreeResp> treeList = catUserTreeRepository.findByPid(pid);
		for (CatUserTreeResp catUserTreeResp : treeList) {
			// 2.判断用户果树状态是否是已送达状态
			if (catUserTreeResp.getTreeStatus() == 4) {
				// 将当前用户信息存到历史表中
				CatUserTreeHistoryResp respHistory = new CatUserTreeHistoryResp(pid);
				catUserTreeHistoryDao.insert(new CatUserTreeHistoryResp(catUserTreeResp.getPid(),
						catUserTreeResp.getLevel(), catUserTreeResp.getFertilizerTotal(),
						catUserTreeResp.getAfertilizer(), catUserTreeResp.getFertilizer(),
						catUserTreeResp.getFirstPlant(), catUserTreeResp.getId(), catUserTreeResp.getTitle(),
						catUserTreeResp.getContent(), catUserTreeResp.getIcUrl(), catUserTreeResp.getTreeStatus()),
						"insertTree");
				// 删除早期果园表中数据
				catUserTreeDao.delete(new CatUserTreeResp(), "deleteTree");
			}
		}
		return treeList;

	}

}
